package com.sprite.utils.http.payload;

import com.sprite.utils.UtilString;
import com.sprite.utils.http.ContentDisposition;
import com.sprite.utils.http.ContentType;
import com.sprite.utils.http.RequestPayload;
import com.sprite.utils.io.UtilIO;
import com.sprite.utils.mimetype.UtilMimeType;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
 * @author Jackl
 * @since 1.2.4
 */
public class SimpleData implements RequestPayload {
    private ContentType contentType;

    private ContentDisposition contentDisposition;

    private Object data;

    @Override
    public void writePayload(OutputStream outputStream) throws IOException {
        if(data instanceof File){
            UtilIO.write(new FileInputStream((File)data), outputStream);
        } else if(data instanceof byte[]){
            outputStream.write((byte[])data);
        }else{
            String charset = contentType!= null?contentType.getCharset():null;
            if(charset == null){
                charset = Charset.defaultCharset().name();
            }
            outputStream.write(String.valueOf(data).getBytes(charset));
        }
    }

    public void setData(Object data){
        setData(data, null);
    }

    public void setData(Object data, String contentType){
        if(UtilString.isNotBlank(contentType)){
            this.contentType = new ContentType(contentType);
        }

        this.data = data;
        if(data instanceof File){
            File file = (File)data;
            contentDisposition = new ContentDisposition();
            String filename = file.getName();
            contentDisposition.putParam("filename", file.getName());
            String mimeType = UtilMimeType.mimeTypeByFileSuffix(filesuffix(filename));
            if(this.contentType == null && UtilString.isNotBlank(mimeType)){
                this.contentType = new ContentType(mimeType);
            }else{
                if(UtilString.isBlank(this.contentType.getMediaType()) && UtilString.isNotBlank(mimeType)){
                    this.contentType.setMediaType(mimeType);
                }
            }

        }
    }

    public void setContentType(ContentType contentType) {
        this.contentType = contentType;
    }

    public ContentDisposition getContentDisposition() {
        return contentDisposition;
    }

    public void setContentDisposition(ContentDisposition contentDisposition) {
        this.contentDisposition = contentDisposition;
    }

    public Object getData() {
        return data;
    }

    private String filesuffix(String file){
        int i = file.lastIndexOf('.');
        if(i >=0){
            return file.substring(i+1);
        }
        return null;
    }

    /**
     * 获取 content type
     *
     * @return
     */
    @Override
    public ContentType getContentType() {
        return contentType;
    }

}


